<template>
  <div class="home">
    <SealAddContinued ref="refSealAddContinued" />
    <SealAddNormal ref="refSealAddNormal" />
    <SealAddByWord ref="refSealAddByWord" />
    <SealAddBatch ref="refSealAddBatch" />
    <SealValidate ref="refSealValidate" />
    <DialogBlock ref="refDialogBlock" />
    <DrawerTest ref="refDrawerTest" />
    <SealAddGap ref="refSealAddGap" />
    <SealRemove ref="refSealRemove" />
    <CopyRight ref="refCopyRight" />
    <SignatureItem />
    <SignatureList v-if="state.isLoadingSignHistory"/>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted, provide } from "vue";

import SealAddNormal from "./components/SealAddNormal.vue";
import SealAddContinued from "./components/SealAddContinued.vue";
import SealAddBatch from "./components/sealAddBatch/SealAddBatch.vue";
import SealAddGap from "./components/SealAddGap.vue";
import SealAddByWord from "./components/sealAddByWord/SealAddByWord.vue";
import SealRemove from "./components/SealRemove.vue";
import SealValidate from "./components/sealValidate/SealValidate.vue";
import SignatureItem from "./components/SignatureItem.vue";
import DialogBlock from "./components/DialogBlock.vue";
import CopyRight from "./components/CopyRight.vue";
import SignatureList from "./components/SignatureList.vue";

import DrawerTest from "./components/DrawerTest.vue";

import $ from "jquery";
import _ from "lodash";
import { useResizeObserver, useDebounceFn } from "@vueuse/core";
import { toast, seal, numbers, http } from "@/utils";
import { helperToolbar } from "./helperToolbar.js";

const refSealAddNormal = ref();
const refSealAddContinued = ref();
const refSealAddBatch = ref();
const refSealAddGap = ref();
const refSealAddByWord = ref();
const refSealRemove = ref();
const refSealValidate = ref();
const refDialogBlock = ref();
const refDrawerTest = ref();
const refCopyRight = ref();

window.refDialogBlock = refDialogBlock;
const state = reactive({
  isLoadingSignHistory: false,
  /** 临时印章 */
  boxTemporarySeal: null,
  /** 签章验证结果 */
  signatureValidateResult: {},
  /** 当前选中的签章 , 在 SignatureItem.vue、 SignatureList.vue 等文件中使用 */
  selectedSignature: {
    signatureDomainId: "",
  },
  movePosition: {
    left: 0,
    top: 0,
  },
  /** 印章按钮群，当前执行操作 */
  sealCurrentOperateName: "",
  methods: {
    resetAll(){
      this.resetPartial();
      state.signatureValidateResult = {};
    },
    resetPartial() {
      state.boxTemporarySeal = null;
      state.selectedSignature.signatureDomainId = "";
      state.methods.setBoxTemporarySeal(null);
      document.getElementById("viewAttachments").dataset.isRequestList = 0
    },
    /** 设置临时印章 */
    setBoxTemporarySeal(newValue) {
      state.boxTemporarySeal = newValue;
      if (newValue === null) {
        $(".box-unfinish").remove();
      }
    },
    /**
     * 设置印章按钮群，当前执行操作
     * @params {String} btnId 对应按钮Id
     * @return
     */
    setSealCurrentOperateName: useDebounceFn(btnId => {
      // console.log("setSealCurrentOperateName btnId", btnId);
      state.sealCurrentOperateName = btnId;
      $("#boxBtnOfSeal .active").removeClass("active");
      if (btnId) {
        $(`#${btnId}`).addClass("active");
      }
    }, 100),
    clearHoverSeal: function () {
      //在 _sealSelector.vue 中实现
    },
    getSignatureList: function () {
      //在 SignatureList.vue 中实现
    },
  },
});

provide("provideHome", state);
window.provideHome = state;
seal.setProvideHome(state);
// window.setBoxTemporarySeal = state.methods.setBoxTemporarySeal;
// window.setSealCurrentOperateName = state.methods.setSealCurrentOperateName;

window.state = state;

/**
 * 是否在可视区
 * @param diffValue  偏差值
 */
$.fn.isInViewport = function (diffValue = 200) {
  //阈值
  let $elem = $(this);
  if ($elem.length == 0) {
    return false;
  }
  var elementTop = $elem.offset().top;
  var elementBottom = elementTop + $elem.outerHeight();

  var viewportTop = $(window).scrollTop();
  var viewportBottom = viewportTop + $(window).height();

  let ret =
    elementBottom > viewportTop + diffValue &&
    elementTop < viewportBottom - diffValue;
  return ret;
};

//高亮显示
$.fn.highLight = function () {
  let $elem = $(this);
  $elem.removeClass("animate__highLight");
  setTimeout(() => {
    $elem.addClass("animate__highLight");
  });
  if (!$elem.data("isBindEnd")) {
    //只绑定一次 ‘animationend’ 事件
    $elem.on("animationend", function () {
      $elem.removeClass("animate__highLight");
    });
    $elem.data("isBindEnd", true);
  }
};

const checkSealUnfinish = () => {
  if (state.boxTemporarySeal) {
    toast.warning("文档中有未加盖的印章，请先确认后再试。");
    if ($(".box-unfinish").length == 0) {
      let { pageNumber } = state.boxTemporarySeal.dataset;
      PDFViewerApplication.pdfLinkService.goToPage(pageNumber);
      //对应页面元素已被清除，还原出来
      restoreBoxTemporarySeal();
    } else {
    }
    let $unfinish = $(".box-unfinish");

    if (!$unfinish.isInViewport()) {
      //不在可视区
      $unfinish[0].scrollIntoView({
        // behavior: "smooth",
        block: "center",
      });
    }
    $unfinish.highLight();
    return false;
  }
  return true;
};

const checkRotate = () => {
  return true;
  if (PDFViewerApplication.pdfViewer.pagesRotation == 0) {
    return true;
  } else {
    toast.warning("文档处于旋转状态，不能加盖印章。");
    return false;
  }
};

let hasBindEvents = false;
/** 绑定页面按钮事件 */
const bindClickEvents = () => {
  if (hasBindEvents) {
    return;
  }
  hasBindEvents = true;

  $("#signComplete").on("click", async function(e) {
    if(!sessionStorage.getItem('transactionId')) {
      return toast.error('文件未进行签章操作！')
    }else {
      let { code, data } = await http.post({
        data: {
          serviceCode: "electronicSealSignature",
          featureCode: "allDone",
          businessData: {
            transactionId: sessionStorage.getItem('transactionId'),
          },
        },
      });
      if(code === "000000" && data) {
        toast.success({text: data})
      }
    }
    return false
  });

  $("#toolbarContainer").on("click", function (event) {
    if ($(event.target).closest("#boxViewFind").length == 0) {
      if ($("#findbar").is(":visible")) {
        //点击的不是“搜索”按钮，且搜索条处于显示状态
        $("#viewFind").click();
      }
    }
  });

  //顶部印章按钮点击事件
  $("#boxBtnOfSeal")
    .on("click.homeBtnEvents", ".unit-item", function (event) {
      // console.log("unit-item click");
      state.methods.setSealCurrentOperateName("");
      state.methods.clearHoverSeal();
      seal.exitAppLinkWhenSealAdd();
    })
    .on("click.homeBtnEvents", "#btnSealAddNormal", function (event) {
      // 快速签章
      if (checkSealUnfinish() && checkRotate()) {
        refSealAddNormal.value.show();
      }
    })
    .on("click.homeBtnEvents", "#btnSealAddContinued", function (event) {
      // 连续签章
      if (checkSealUnfinish() && checkRotate()) {
        refSealAddContinued.value.show();
      }
    })
    .on("click.homeBtnEvents", "#btnSealAddBatch", function (event) {
      //多页签章
      if (checkSealUnfinish() && checkRotate()) {
        refSealAddBatch.value.show();
      }
    })
    .on("click.homeBtnEvents", "#btnSealAddGap", function (event) {
      //骑缝签章
      //当前文档页码数
      if (PDFViewerApplication.pdfDocument.numPages == 1) {
        toast.warning("文档只有一页，不能加盖骑缝章。");
        return;
      }
      if (checkSealUnfinish() && checkRotate()) {
        refSealAddGap.value.show();
      }
    })
    .on("click.homeBtnEvents", "#btnSealAddByWord", function (event) {
      //关键字签章
      if (checkSealUnfinish() && checkRotate()) {
        refSealAddByWord.value.show();
      }
    })
    .on("click.homeBtnEvents", "#btnSealRemove", function (event) {
      //撤章
      if (checkSealUnfinish()) {
        refSealRemove.value.show();
      }
    })
    .on("click.homeBtnEvents", "#btnSealValidate", function (event) {
      //验签
      if (checkSealUnfinish()) {
        refSealValidate.value.show();
      }
    });

  //旋转点击事件
  $("#pageRotateCw_mirror").on("click", function () {
    if (checkSealUnfinish()) {
      $("#pageRotateCw").trigger("click");
    }
  });

  //搜索栏 关闭按钮点击事件
  $("#findClose").on("click", function () {
    $("#viewFind").click();
  });

  $("#copyRight").on("click", function () {
    refCopyRight.value.show();
  });
};

const restoreBoxTemporarySeal = () => {
  let { boxTemporarySeal } = state;
  if (boxTemporarySeal) {
    //还原临时印章
    // console.log("还原临时印章...");
    boxTemporarySeal.classList.remove("hidden");

    let { pageNumber, sealType } = boxTemporarySeal.dataset;
    let $page = $(`.page:eq(${pageNumber - 1})`);
    let pageCurrentWidth = $page.width();
    let pageCurrentHeight = $page.height();
    $page.append(boxTemporarySeal);

    if (sealType == "gap") {
      //骑缝章
      let elBoxConfirmSeal = $(".box-confirm-seal", boxTemporarySeal)[0];
      let { top, pageHeight } = elBoxConfirmSeal.dataset;
      //换算出当前top
      let curTop = numbers.division(
        numbers.multiplication(top, pageCurrentHeight),
        pageHeight
      );

      _.assign(state.movePosition, {
        left: 0,
        top: curTop,
      });
      seal.move(elBoxConfirmSeal, {
        left: 0,
        top: curTop,
      });

      setTimeout(() => {
        $("#viewerContainer").scrollLeft(1000);
      }, 500);
    } else {
      //非骑缝章
      let { left, top, pageWidth, pageHeight } = boxTemporarySeal.dataset;
      //换算出当前left
      let curLeft = numbers.division(
        numbers.multiplication(left, pageCurrentWidth),
        pageWidth
      );
      //换算出当前top
      let curTop = numbers.division(
        numbers.multiplication(top, pageCurrentHeight),
        pageHeight
      );
      _.assign(state.movePosition, {
        left: curLeft,
        top: curTop,
      });

      seal.move(boxTemporarySeal, {
        left: curLeft,
        top: curTop,
      });
    }
  }
};

const bindViewerResizeEvents = () => {
  let viewer = document.getElementById("viewer");

  useResizeObserver(viewer, function () {
    let { boxTemporarySeal } = state;
    if (boxTemporarySeal) {
      boxTemporarySeal.classList.add("hidden");
    }
  });

  useResizeObserver(
    viewer,
    useDebounceFn(() => {
      restoreBoxTemporarySeal();
    }, 500)
  );
};

const bindMessageEvents = () => {
  window.addEventListener("message", function (event) {
    let execStr = event.data;
    if (typeof execStr == "string") {
      // console.log("message", execStr);
      let exec = JSON.parse(execStr);
      let { method, data } = exec;
      //btnYxxxxx 模式方法列表
      let btnPatternMethodList = [
        "sealAddNormal",
        "sealAddContinued",
        "sealAddBatch",
        "sealAddGap",
        "sealAddByWord",
        "sealRemove",
        "sealValidate",
      ];
      //方法原名模式方法列表
      let rawPatternMethodList = ["print", "download"];
      if ("init" == method) {
        //初始化
        // console.log("init event ", data);
        sessionStorage.removeItem('transactionId')
        seal.initEditor(data);
      } else if (method == "rotateRight") {
        //右旋转
        $(`#pageRotateCw_mirror`).trigger("click");
      } else if (btnPatternMethodList.includes(method)) {
        let btnId =
          "btn" + method.substr(0, 1).toUpperCase() + method.substr(1);
        $(`#${btnId}`).trigger("click");
      } else if (rawPatternMethodList.includes(method)) {
        $(`#${method}`).trigger("click");
      }
    }
  });
};

const bindPrintEvents = () => {
  window.addEventListener("beforeprint", () => {
    $("#print").addClass("active");
    seal.setParentDocumentTitle();
  });
  window.addEventListener("afterprint", () => {
    $("#print").removeClass("active");
    seal.resetParentDocumentTitle();
  });
};

const bindTest = () => {
  $("#btnDrawer").on("click", () => {
    console.log("provideHome",window.provideHome);
    console.log("signatureList.list", signatureList);
  });
};

onMounted(() => {
  bindMessageEvents();
  bindClickEvents();
  bindViewerResizeEvents();
  bindPrintEvents();
  bindTest();
  helperToolbar.watchToolbarChange();
});

window.seal = seal;
</script>
<style lang="scss">
.zhongzhao.no-active {
  .hover-seal {
    opacity: 0.5;
  }
}

.box-rotation {
  &[data-shower-rotation="0"] {
    .shower {
      transform: rotate(0deg);
    }
  }
  &[data-shower-rotation="90"] {
    .shower {
      transform: rotate(90deg);
    }
  }
  &[data-shower-rotation="180"] {
    .shower {
      transform: rotate(180deg);
    }
  }
  &[data-shower-rotation="270"] {
    .shower {
      transform: rotate(270deg);
    }
  }
}

.box-confirm-seal {
  @apply absolute left-0 top-0 z-20;
  width: var(--sealWidth);
  height: var(--sealHeight);
  img {
    @apply block;
  }
  &.seal-add-continued {
    .box-confirm-btn {
      display: none;
    }
  }
  .box-confirm-btn {
    @apply justify-around absolute;
    bottom: calc(calc(2px * calc(var(--scale-factor) / 1.3)));
    right: calc(calc(2px * calc(var(--scale-factor) / 1.3)));
    transform: scale(calc(var(--scale-factor) / 1.3));
    transform-origin: right bottom;
    img {
      width: 24px;
      height: 24px;
      margin-left: 6px;
    }
    .btn-item {
      &:hover {
        filter: brightness(1.3);
      }
    }
  }
  &:hover {
    // box-shadow: 0 0 0px 1px #ff9313;
    background: rgba(255, 147, 19, 0.2);
    outline: dashed 2px #ff9313;
  }
}
.drag-area {
  outline: dashed 1px #276ef9;
  background: #eff6ff;
}
</style>
